package com.heima.schedule.service.impl;
/*
    
 需求描述：
 @Author: wang
 @Date: 2022/10/20 10:00
 
 */

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskInfoLogsMapper;
import com.heima.schedule.mapper.TaskInfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Slf4j
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskInfoMapper taskinfoMapper;
    @Autowired
    private TaskInfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {
        //持久化保存到数据库
        Boolean aBoolean = addTaskDB(task);
        if (!aBoolean) {
            throw new RuntimeException("保存数据到数据库失败");
        }

        // 放进缓存
        addTaskToCache(task);


        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public Boolean cancelTask(Long taskId) {
        boolean flag = false;
        Task task = delDB(taskId, ScheduleConstants.CANCELLED);
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }


        return flag;
    }

    /**
     * 拉取任务
     *
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public Task poolTask(Integer taskType, Integer priority) {
        String key = taskType + "_" + priority;
        Task task = null;
        String task_JSON = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotEmpty(task_JSON)) {
            task = JSON.parseObject(task_JSON, Task.class);
            delDB(task.getTaskId(), ScheduleConstants.EXECUTED);
        }

        return task;
    }


    /**
     * 定时将future里的任务刷新到topic中
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("正在同步数据");
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("同步数据成功");
                }
            }
            // 运行完成后释放锁
            cacheService.releaseLock("FUTURE_TASK_SYNC");
        }
    }

    /**
     * 将五分钟内要执行的任务同步到redis中
     */
    @Override
    @PostConstruct
    @Scheduled(cron = "0 */2 * * * ?")//每五分钟自动执行一次
    public void reloadData() {

        clearCache();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 5);
        Date time = instance.getTime();
        List<Taskinfo> tasks = taskinfoMapper
                .selectList(Wrappers.<Taskinfo>lambdaQuery()
                        .le(Taskinfo::getExecuteTime, time));
        if (tasks != null && tasks.size() > 0) {
            for (Taskinfo taskInfo : tasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskInfo, task);
                task.setExecuteTime(taskInfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
        log.info("数据库任务已经同步到了缓存中");


    }

    /**
     * 清理缓存数据
     */
    public void clearCache() {
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }

    /**
     * 删除redis里的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除info数据 并修改logs中任务的状态
     *
     * @param taskId
     * @return
     */
    private Task delDB(Long taskId, Integer status) {

        int i = taskinfoMapper.deleteById(taskId);
        TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskId);
        logs.setStatus(status);
        int i1 = taskinfoLogsMapper.updateById(logs);
        Task task = new Task();
        BeanUtils.copyProperties(logs, task);
        task.setExecuteTime(logs.getExecuteTime().getTime());
        return task;
    }

    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        //获取当前和未来五分钟的时间
        long currentTimeMillis = System.currentTimeMillis();
        // 获取未来五分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long futureTimeMillis = calendar.getTimeInMillis();

        // 判断任务执行时间是否小于或者等于当前时间
        if (task.getExecuteTime() <= currentTimeMillis) {
            String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        }
        // 判断任务执行时间是否小于或者等于当前时间
        else if (task.getExecuteTime() <= futureTimeMillis) {
            String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 保存数据到数据库
     *
     * @param task
     */
    private Boolean addTaskDB(Task task) {
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        int insert = taskinfoMapper.insert(taskinfo);
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, taskinfoLogs);
        taskinfoLogs.setVersion(1);
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
        // 控制两个表的taskId一致
        taskinfoLogs.setTaskId(taskinfo.getTaskId());
        taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
        int insert1 = taskinfoLogsMapper.insert(taskinfoLogs);
        task.setTaskId(taskinfo.getTaskId());
        return insert == 1 && insert1 == 1;
    }
}
